#!/usr/bin/python
import RPi.GPIO as GPIO           # import RPi.GPIO module
import time
import os
import subprocess
GPIO.setmode(GPIO.BCM)            # choose BCM or BOARD
GPIO.setup(23, GPIO.OUT)  # set a port/pin as an output
GPIO.setup(24, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) # set a port/pin as an input
f1 = os.popen('lpq -a')
printq = f1.read()
printer_state = GPIO.input(24)

if "Job" in printq:
print "Job(s) are in print queue"
  printer_state = GPIO.input(24)
  print "Printer state is:", printer_state
  if printer_state == 1:
    while printer_state == 1:  #1 equals off
      printer_state = GPIO.input(24)
      GPIO.output(23, 1)  #Turn on printer
      time.sleep(45)
      print "Printer is started"
      os.popen('cupsenable Pi_Deskjet_F4400') ## Restart print queue if needed
      time.sleep(45)
      if "no entries" in printq:
        print "Queue is now empty, printing complete."
      else:
        print "Done printing, this is the else statement."    
  else:
    print "Else statement when printer was off"
  ## Turn off printer
  ## Check if successful, if not, send signal again to power off.
  print "Shutting down printer."
  
  printer_state = GPIO.input(24)
  
  while printer_state == 0:  #0 equals on
    printer_state = GPIO.input(24)
    GPIO.output(23, 0)  #Turn printer off
    time.sleep(10)
  print "Printer will sleep now."  

else:
#if "no entries" in printq:
  print "Queue is empty"
  print "Done"

GPIO.cleanup()